package com.lsw.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.util.DisplayMetrics;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


/**
 * 设备和app信息工具
 *
 * @ClassName: DeviceUtil
 * @Description:
 * @date 2014-7-2 上午12:33:40
 */
public class DeviceUtil {
    /**
     * 获取当前应用的的包信息
     *
     * @param context
     * @return
     */
    public static PackageInfo getMPackageInfo(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            return packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取应用版本号
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        int versionCode = packInfo.versionCode;
        return versionCode;
    }

    /**
     * 获取应用版本名称
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        String versionName = packInfo.versionName;
        return versionName;
    }

    /**
     * @param VersionName  当前版本号
     * @param VersionName1 服务器版本号
     * @return 是否需要更新
     */
    public static boolean isUpdataVersion(String VersionName, String VersionName1) {
        if (VersionName == null || VersionName1 == null)
            return false;
        VersionName = VersionName.replace(".", "");
        VersionName1 = VersionName1.replace(".", "");
        if (VersionName.length() > VersionName1.length()) {
            int s = VersionName.length() - VersionName1.length();
            for (int i = 0; i < s; i++) {
                VersionName1 += "0";
            }
        } else if (VersionName.length() < VersionName1.length()) {
            int s = VersionName1.length() - VersionName.length();
            for (int i = 0; i < s; i++) {
                VersionName += "0";
            }
        }
        return Float.valueOf(VersionName1) > Float.valueOf(VersionName);
    }

    /***
     * 获取url 指定name的value;
     *
     * @param url
     * @param name
     * @return
     */
    public static String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }

    /**
     * 判断 用户是否安装微信客户端
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断 用户是否安装QQ客户端
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 打开应用市场指定应用的详情页
     *
     * @param context     上下文
     * @param packageName 包名
     */
    public static void openApplicationMarket(Context context, String packageName) {
        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName)));
    }

    /**
     * 打开京东客户端指定商铺
     *
     * @param context 上下文
     * @param shopId  商铺ID
     */
    public static void openJdShop(Context context, long shopId) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("openApp.jdMobile://virtual?params={\"category\":\"jump\",\"des\":\"jshopMain\",\"shopId\":\"" + shopId + "\",\"sourceType\":\"M_sourceFrom\",\"sourceValue\":\"dp\"}"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 打开京东客户端指定商品详情页
     *
     * @param context 上下文
     * @param goodsId 商品ID
     */
    public static void openJdGoods(Context context, long goodsId) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("openApp.jdMobile://virtual?params={\"category\":\"jump\",\"des\":\"productDetail\",\"skuId\":\"" + goodsId + "\",\"sourceType\":\"JSHOP_SOURCE_TYPE\",\"sourceValue\":\"JSHOP_SOURCE_VALUE\"}"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 打开淘宝客户端指定商铺
     *
     * @param context 上下文
     * @param shopId  商铺ID
     */
    public static void openTaoBaoShop(Context context, long shopId) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("taobao://shop.m.taobao.com/shop/shop_index.htm?shop_id=" + shopId));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 打开淘宝客户端指定商品详情页
     *
     * @param context 上下文
     * @param goodsId 商品ID
     */
    public static void openTaoBaoGoods(Context context, long goodsId) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("taobao://item.taobao.com/item.htm?id=" + goodsId));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 打开天猫客户端指定商铺
     *
     * @param context 上下文
     * @param shopId  商铺ID
     */
    public static void openTmallShop(Context context, long shopId) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tmall://page.tm/shop?shopId=" + shopId));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 打开天猫客户端指定商品详情页
     *
     * @param context 上下文
     * @param goodsId 商品ID
     */
    public static void openTmallGoods(Context context, long goodsId) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tmall://tmallclient/?{\"action\":”item:id=" + goodsId + "”}"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private enum ApplicationType {
        //所有应用、非系统应用、系统应用
        allApplication, nonSystemApplication, systemApplication
    }

    /**
     * 获取设备的应用信息
     */
    private static List<Application> getApplicationInfo(Context context, ApplicationType applicationType) {
        List<Application> applicationList = new ArrayList<>();
        List<PackageInfo> packageInfoList = context.getPackageManager().getInstalledPackages(0);
        for (PackageInfo packageInfo : packageInfoList) {
            Application application = new Application(packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString(), packageInfo.packageName,
                    packageInfo.applicationInfo.loadIcon(context.getPackageManager()), packageInfo.versionName);
            switch (applicationType) {
                case allApplication:
                    applicationList.add(application);
                    break;
                case systemApplication:
                    if (isSystemApplication(packageInfo)) {
                        applicationList.add(application);
                    }
                    break;
                case nonSystemApplication:
                    if (!isSystemApplication(packageInfo)) {
                        applicationList.add(application);
                    }
                    break;
            }
        }
        return applicationList;
    }

    /**
     * 判断是否是系统应用
     */
    private static Boolean isSystemApplication(PackageInfo packageInfo) {
        return (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
    }

    /**
     * 获取设备所有的应用
     */
    public static List<Application> getAllApplication(Context context) {
        return getApplicationInfo(context, ApplicationType.allApplication);
    }

    /**
     * 获取设备所有的系统应用
     */
    public static List<Application> getAllSystemApplication(Context context) {
        return getApplicationInfo(context, ApplicationType.systemApplication);
    }

    /**
     * 获取设备所有的非系统应用
     */
    public static List<Application> getAllNonSystemApplication(Context context) {
        return getApplicationInfo(context, ApplicationType.nonSystemApplication);
    }

    /**
     * 根据应用包名获取应用名
     */
    public static String getApplicationNameByPackageName(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        try {
            return pm.getApplicationLabel(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA)).toString();
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }

    /**
     * 判断指定包名的应用是否存在
     */
    public static boolean appExist(Context context, String packageName) {
        List<PackageInfo> packageInfoList = context.getPackageManager().getInstalledPackages(0);
        for (PackageInfo packageInfo : packageInfoList) {
            if (packageInfo.packageName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }
}
